<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Mews\Captcha\Facades\Captcha;
use App\Http\Requests\Admin\AuthLoginRequest;
use App\Services\Admin\AuthService;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller
{
    // 初始化 admin 账号
    public function init()
    {
        $data = AuthService::init();

        return $this->success(data: $data);
    }

    public function captcha()
    {

        $captcha = Captcha::create('math', true);

        return $this->success(data: [
            'captchaKey' => $captcha['key'],
            'captchaBase64' => $captcha['img']
        ]);
    }

    public function login(AuthLoginRequest $request)
    {

        $validated = $request->validated();

        $data = AuthService::login($validated);

        return $this->success(data: $data);
    }


    public function refreshToken(Request $request)
    {

        $oldRefreshToken = $request->validate([
            'refreshToken' => 'required'
        ])['refreshToken'];

        $data = AuthService::refreshToken($oldRefreshToken);

        $status = $data['status'];

        if ($status !== 200) {
            return $this->error(status: $status, data: $data['data']);
        }

        return $this->success(data: $data['data']);
    }

    public function logout(Request $request)
    {

        try {
            // 将 token 信息注销
            Auth::logout();

            // 获取并失效 refresh_token（客户端从请求体传递）
            $refreshToken = $request->input('refreshToken');

            if ($refreshToken) {
                JWTAuth::setToken($refreshToken)->invalidate(); // 使 refresh_token 失效
            }

            return $this->success();
        } catch (\Exception $e) {
            return $this->error(msg: '退出失败：' . $e->getMessage());
        }
    }
}
